package com.ipworkbench.common.db;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import com.ipworkbench.common.util.IPWException;

/**
 * 数据库连接工厂
 * 			使用proxool连接池
 * 
 * @author zhangfaheng
 *
 * @date May 15, 2010
 */
public class ConnectionFactory{
	
	
	// 实例化静态连接工厂对象
	private static ConnectionFactory instance = new ConnectionFactory();
	
    private ConnectionFactory() {
    }

    public static ConnectionFactory getInstace() {
        return instance;
    }

    /**
     * 从当前线程里获取连接
     * 
     * @return Connection
     */
    public static Connection getConnection() {
        Connection conn = (Connection) TransactionManager.local.get();
        return conn;
    }

  
    /**
     * 从proxool抓取连接
     * 
     * @return
     * 
     * @throws IPWException
     */
    public Connection takeConnection() throws IPWException{
        Connection conn = null;
    	try {
			Class.forName("org.gjt.mm.mysql.Driver");
			conn = DriverManager.getConnection("proxool.MysqlCP");
		} catch (Exception e) {
			throw new IPWException("抓取数据库连接池连接异常",e);			
		}
		return conn;
    }

    
       
    /**
     * 关闭数据库资源
     * 
     * @param rs
     * @param st
     * @param ps
     * @param cs
     * @throws IPWException
     */
    protected void close(ResultSet rs, Statement st,PreparedStatement ps
    		,CallableStatement cs) throws IPWException {
    	try {
    		if(rs != null){
    			rs.close();
    			rs = null;
    		}
    		if(st != null){
    			st.close();
    			st = null;
    		}	
    		if(ps != null){
    			ps.close();
    			ps = null;
    		}	
    		if(cs != null){
    			cs.close();
    			cs = null;
    		}
		} catch (Exception e) {
			throw new IPWException("关闭数据库资源出错",e);
		}
    	
    }


}
